// 云函数入口文件  摄影套系相关操作
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})
const db = cloud.database();
const _ = db.command;

add = async (event, context) => {
  if (!event.data) throw new Error("参数data为空");
  if (!event.data._openid) {
    event.data._openid = context.OPENID
  }
  event.data.createtime = Date.now();
  let res = await db.collection(event.table).add({
    data: event.data
  });
  if(event.msg){
    await sendMessage(event, context);
  }
  return res;
}

update = async (event, context) => {
  if (typeof (event.data) !== 'object') throw new Error("参数data为空");
  let _id = event.data._id;
  console.log('传入msg：',event.msg);
  if (!_id) {
    return add(event, context);
  }
  if (event.data._id) {
    delete event.data._id;
  }
  event.data.updatetime = Date.now();
  let res = await db.collection(event.table).doc(_id).update({
    data: event.data
  });

  if(event.msg){
    await sendMessage(event, context);
  }
  return res
}

set = async (event, context) => {
  if (typeof (event.data) !== 'object') throw new Error("参数data为空");
  let _id = event.data._id;
  if (!_id) throw new Error("参数_id为空");
  delete event.data._id;
  event.data.updatetime = Date.now();
  return db.collection(event.table).doc(_id).set({
    data: event.data
  });
}

remove = async (event, context) => {
  if (!event._id) throw new Error("参数_id为空");
  return db.collection(event.table).where({
    _id: event._id
  }).remove();
}

get = async (event, context) => {
  let skip = event.skip == undefined ? 0 : parseInt(event.skip);
  if (isNaN(skip)) skip = 0;
  let where = {};
  let field = event.field;
  if (typeof (field) !== "object") field = {}
  let limit = event.limit || 20;
  if (typeof event.where == 'object') where = event.where;
  let order = {
    field: "createtime",
    by: 'desc'
  };
  if (event.order) {
    order = event.order;
  }
  console.log('where==',where)
  return await db.collection(event.table).where(where).field(field).orderBy(order.field, order.by).skip(skip).limit(limit).get();
}
sendMessage = async (event, context) => {
  if (!event.msg) return;
 
  try {
    await cloud.openapi.subscribeMessage.send({
      touser: event.msg._openid,
      templateId: event.msg.templateId,
      miniprogram_state: 'trial',
      page: event.msg.page,
      data: event.msg.data,
    })
  } catch (error) {
    console.log(error)
  }
}

// 云函数入口函数
/**
 * 摄影套系相关操作
 * 只适配普通操作，对于复杂操作，需要另行定义
 * @param {*} op: 'add', 'update', 'remove', 'get' , 'set'
 * @param {*} data: {'_id': 'aaa', ... } add操作不需要_id,remove必须带_id, get操作如果带有data参数则视为查询条件，查询条件如果为数组，则视为范围查询
 * get 参数如果带有参数 skip，可以取指定页码的数据 ，带where，会用作查询条件
 * update 对象时，如果data不带 _id，将自动调用add，所以前端可以直接调用 update
 * set 操作必须带有 _id，如果数据不存在则自动添加，否则直接更新
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  if (!event.op || !event.table) throw Error("参数错误");
  console.log("传入参数", event.op, event.table,event);
  switch (event.op) {
    case 'add':
      return add(event, wxContext)
    case 'update':
      return update(event, wxContext);
    case 'set':
      return set(event, wxContext);
    case 'remove':
      return remove(event, wxContext);
    case 'get':
      console.log("where", event.where);
      return get(event, wxContext);
    default:
      throw Error("未知的 op : " + event.op);
  }
}